﻿@page "/account/login"
@using BXJG.Common.RCL
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Cookies
@using ZLJ.Application.Common.Share.Auth
@using ZLJ.Application.Common.Share.Models.TokenAuth
@inject NavigationManager nav;

@layout NullLayout

<PageTitle>登录</PageTitle>


<EditForm Model="model" method="post" OnValidSubmit="LoginUser" FormName="login">
    租户： <InputText @bind-Value="model.TenancyName" />
    登录名： <InputText @bind-Value="model.UserNameOrEmailAddress" />
    密码： <InputText @bind-Value="model.Password" type="password" />
    记住我：<InputCheckbox @bind-Value="model.RememberClient" />
    <button type="submit">登录</button>
</EditForm>

@code {

    [SupplyParameterFromForm]
    public AuthenticateModel model { get; set; } = new AuthenticateModel
        {
            Password = "123qwe",
            RememberClient = true,
            TenancyName = "default",
            UserNameOrEmailAddress = "admin"
        };

    [SupplyParameterFromQuery]
    public string ReturnUrl { get; set; }
    [Inject]
    public ITokenAuthAppService TokenAuthAppService { get; set; }

    // [Inject]
    // public Microsoft.AspNetCore.Authentication.IAuthenticationService AuthorizationService { get; set; }

    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;

    public async Task LoginUser()
    {
        var r = await TokenAuthAppService.Authenticate(model);

        //巨坑，new ClaimsIdentity时必须指定身份验证类型，否则HttpContext.User.Identity.IsAuthenticated一直是false
        await this.HttpContext.SignInAsync(new System.Security.Claims.ClaimsPrincipal(new ClaimsIdentity([new Claim(nameof(r.AccessToken),r.AccessToken),
                                                                                                          new Claim(nameof(r.EncryptedAccessToken),r.EncryptedAccessToken),
                                                                                                          new Claim(nameof(r.UserId),r.UserId.ToString()),
                                                                                                          new Claim(nameof(r.ExpireInSeconds),r.ExpireInSeconds.ToString())], CookieAuthenticationDefaults.AuthenticationScheme)),
                                           new AuthenticationProperties{IsPersistent = model.RememberClient,
                                                                        //cookie过期是单独指cookie，这里的是指
                                                                        ExpiresUtc = TimeProvider.System.GetUtcNow().AddSeconds(r.ExpireInSeconds)});
        // await AuthorizationService.SignInAsync(this.HttpContext,
        //                                        default,
        //                                        new System.Security.Claims.ClaimsPrincipal(new ClaimsIdentity([new Claim(nameof(r.AccessToken),r.AccessToken),
        //                                                                                                       new Claim(nameof(r.EncryptedAccessToken),r.EncryptedAccessToken),
        //                                                                                                       new Claim(nameof(r.UserId),r.UserId.ToString()),
        //                                                                                                       new Claim(nameof(r.ExpireInSeconds),r.ExpireInSeconds.ToString())])),
        //                                        new AuthenticationProperties
        //                                            {
        //                                                IsPersistent = model.RememberClient,
        //                                                //cookie过期是单独指cookie，这里的是指
        //                                                ExpiresUtc = TimeProvider.System.GetUtcNow().AddSeconds(r.ExpireInSeconds)
        //                                            });

        // //var zh =
        // var loginResult = await GetLoginResultAsync(
        //     model.UserNameOrEmailAddress,
        //     model.Password,
        //     model.TenancyName //先粗暴点就这么写吧，后期参考zero登陆租户原理调整
        //                       //GetTenancyNameOrNull()
        // );
        // //await base.HttpContext.SignInAsync("Identity.Application",
        // //                                   new System.Security.Claims.ClaimsPrincipal(loginResult.Identity), new AuthenticationProperties
        // //                                   {
        // //                                       IsPersistent = model.RememberClient
        // //                                   });
        // await signInManager1.SignInAsync(loginResult.Identity, true  );
        // // return Redirect(returnUrl);
        nav.NavigateTo(ReturnUrl, true);
    }
    // private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName)
    // {
    //     var loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName);

    //     switch (loginResult.Result)
    //     {
    //         case AbpLoginResultType.Success:
    //             return loginResult;
    //         default:
    //             throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
    //     }
    // }
}